// 保存棋盘格子
import { ecs } from '../framework/assets/libs/ecs/ECS';
import { CellModelComponent } from "./cellModelComponent";
import { CellView } from "../cccomponent/cellView";
import {
    ExchangeCellComponent,
    MoveCellComponent,
    SelectCellComponent,
    CellDieComponent,
    UpdateCellStatusComponent, AudioSwapComponent
} from "./utilsComponent";
import { CellStatus } from "../cccomponent/enum";

@ecs.register('CellEntity')
export class CellEntity extends ecs.Entity {
    // model名要跟GridModelComponent 注册的名字一致，才能自动挂载
    CellModel!: CellModelComponent;
    CellView: CellView;

    protected init() {
        // 添加组件
        this.add(CellModelComponent);
    }

    click(isSelect: boolean) {
        if (!this.has(SelectCellComponent)) {
            this.add(SelectCellComponent);
        }
        this.get(SelectCellComponent).selectToggle = isSelect;
    }

    // 移动到第几行,第几列
    moveTo(x: number, y: number, playTime: number, delayTime: number) {
        if (!this.has(MoveCellComponent)) {
            this.add(MoveCellComponent);
        }
        const comp = this.get(MoveCellComponent)
        comp.x = x;
        comp.y = y;
        comp.playTime = playTime;
        comp.delayTime = delayTime;
    }

    // 交换
    exchange() {
        if (!this.has(ExchangeCellComponent)) {
            this.add(ExchangeCellComponent);
        }
        const comp = this.get(ExchangeCellComponent);
        comp.originX = this.CellModel.x;
        comp.originY = this.CellModel.y;
        // 添加交换音效
        this.add(AudioSwapComponent);
    }

    moveBack(playTime: number, delayTime: number) {
        const comp = this.get(ExchangeCellComponent)!;
        this.moveTo(comp.originX, comp.originY, playTime, delayTime);
    }

    toDie(delayTime: number) {
        if (!this.has(CellDieComponent)) {
            const comp = this.add(CellDieComponent);
            comp.delayTime = delayTime;
        }
    }

    // 新状态
    updateStatus(newStatus: CellStatus) {
        if (!this.has(UpdateCellStatusComponent)) {
            this.add(UpdateCellStatusComponent);
        }
        const comp = this.get(UpdateCellStatusComponent);
        comp.newStatus = newStatus;
        // 更新新状态，参与消除
        this.CellModel.status = newStatus;
    }
}
